import json
import logging
import sys

import requests

from comm.dateTime import nowData
from comm.dbConnect import dbJonOne
from setting import openDbBase

class yxkApiList:
    dbproconfig = openDbBase()
    # 第三方应用系统编码，即appId
    client_id = dbproconfig['yxkapi']['client_id']
    # 第三方应用AccessToken认证密钥，即appSecret
    client_secret = dbproconfig['yxkapi']['client_secret']
    # 第三方应用代理用户的用户名
    username = dbproconfig['yxkapi']['username']
    # 数据中心id
    accountId = dbproconfig['yxkapi']['accountId']
    # 语言字串： zh_CN，zh_TW、en_US等。 默认系统默认语言，查询接口会返回对应的多语言文本字段
    language = dbproconfig['yxkapi']['language']
    # 随机数
    nonce = dbproconfig['yxkapi']['nonce']
    prdt_time = dbproconfig['yxkapi']['prdt_time']
    # 接口请求中的固定值
    xacgwidentity = dbproconfig['yxkapi']['xacgwidentity']
    # 请求地址
    apiAdd = dbproconfig['yxkapi']['apiAdd']


    @classmethod
    def getToken(cls):
        import os
        # 当前脚本作为主程序运行时的路径
        if getattr(sys, 'frozen', False):
            entry_point_path = sys.executable
            # print(111,entry_point_path)
        else:
            entry_point_path = sys.modules['__main__'].__file__
            # print(222,entry_point_path)
        entry_point_abs_path = os.path.dirname(os.path.abspath(entry_point_path))
        # print("入口文件路径:", entry_point_abs_path)
        entry_point_abs_path = entry_point_abs_path + '\\api_yxk__init__.txt'
        if os.path.exists(entry_point_abs_path):
            # 文件存在读取文件中的wms token
            with open(entry_point_abs_path, 'r', encoding="utf-8") as file:
                content = file.read()
                try:
                    apiTokenObj = json.loads(content)
                except Exception as e:
                    logging.info('yxk读取缓存中的token失败' + repr(e))
                    return None, "yxk读取缓存中的token失败" + repr(e)
                # 文件中不存在wms的token则登录
                if "yxk" not in apiTokenObj.keys():
                    # print("不存在wms的token")
                    logging.info('不存在yxk的token')
                    token, err = cls.login()
                    if err != None:
                        return None, err
                    getToken = {}
                    getToken["token"] = token
                    getToken["time"] = nowData(hour=1)
                    apiTokenObj["yxk"] = getToken
                    # 将token写入到文件中
                    with open(entry_point_abs_path, 'w', encoding="utf-8") as file:
                        file.write(json.dumps(apiTokenObj))
                # 判断token是否过期
                # print(apiTokenObj['yxk']["time"],"===", nowData())
                if apiTokenObj['yxk']["time"] <= nowData():
                    logging.info('yxk的token过期重新登录获取')
                    # token过期重新获取token
                    # print("wms的token过期重新获取token")
                    token, err = cls.login()
                    if err != None:
                        return None, err
                    with open(entry_point_abs_path, 'w', encoding="utf-8") as file:
                        getToken = {}
                        getToken["token"] = token
                        getToken["time"] = nowData(hour=1)
                        apiTokenObj["yxk"] = getToken
                        # 将token写入到文件中
                        print(apiTokenObj)
                        file.write(json.dumps(apiTokenObj))
                token = apiTokenObj['yxk']["token"]
        else:
            # print("文件不存在")
            logging.info('yxk的token文件不存在登录获取token')
            token, err = cls.login()
            if err != None:
                return None, err
            with open(entry_point_abs_path, 'w', encoding="utf-8") as file:
                getToken = {}
                getToken["token"] = token
                getToken["time"] = nowData(hour=1)
                apiTokenObj = {}
                apiTokenObj["yxk"] = getToken
                # 将token写入到文件中
                file.write(json.dumps(apiTokenObj))
        return token, None
    @classmethod
    def login(cls):
        url = cls.apiAdd + "oauth2/getToken"
        # url = cls.apiAdd + "OAuth2/GetAuthorizeCode"
        header = {
            "Content-Type":"application/json"
        }
        params = {}
        params['client_id'] = cls.client_id
        params['client_secret'] = cls.client_secret
        params['username'] = cls.username
        params['accountId'] = cls.accountId
        params['nonce'] = cls.nonce
        params['language'] = cls.language
        params['timestamp'] = nowData()
        # print(url)
        r = requests.post(url,json=params,headers=header)
        if r.status_code != 200:
            # print(r.json())
            # print(r.status_code)
            return None, 'api接口登录请求失败' + json.dumps(r.json(),ensure_ascii=False)
        # print(r.status_code)
        resData = r.json()
        # print(resData)
        if resData['status'] != True:
            return None,json.dumps(r.json(),ensure_ascii=False)
        return resData['data']["access_token"],None

    # 物料批量查询
    @classmethod
    def partBatGet(cls,data):
        """

        :param data: 表身参数
        :param token: 请求头token
        :return:
        """
        url = cls.apiAdd + "v2/eky4/basedata/bd_material/batchQueryNew"
        jsonData = data
        # pprint(jsonData)
        # print(json.dumps(jsonData,ensure_ascii=False))
        token , err = cls.getToken()
        if err is not None:
            return None,'获取token失败' + err
        header = {
            # "Content-Type": "application/json",
            "accesstoken":token,
            "x-acgw-identity":str(cls.xacgwidentity)
        }
        jsonData['start_eky4_shrq'] = nowData(minute=-cls.prdt_time,day=-1)
        print(nowData(minute=-cls.prdt_time))
        r = requests.post(url, data=jsonData, headers=header)
        if r.status_code != 200:
            return None, '接口请求失败' + json.dumps(r.json(),ensure_ascii=False)
        resData = r.json()
        # print(resData)
        if resData['status'] != True:
            return None, '接口请求失败' + json.dumps(r.json(),ensure_ascii=False)
        data = {}
        data['data'] = resData['data']["rows"]
        data['pageNo'] = resData['data']["pageNo"]
        data['lastPage'] = resData['data']["lastPage"]
        data['totalCount'] = resData['data']["totalCount"]
        data['lastPage'] = resData['data']["lastPage"]
        return data, None

    @classmethod
    def osCkAddPost(cls, data):
        """

        :param data: 表身参数
        :param token: 请求头token
        :return:
        """
        url = cls.apiAdd + "v2/im/im_saloutbill/batchAdd"
        jsonData = data
        # pprint(jsonData)
        # print(json.dumps(jsonData,ensure_ascii=False))
        token, err = cls.getToken()
        if err is not None:
            return None, '获取token失败' + err
        header = {
            # "Content-Type": "application/json",
            "accesstoken": token,
            "x-acgw-identity": str(cls.xacgwidentity)
        }
        # jsonData['start_eky4_shrq'] = nowData(minute=-cls.prdt_time, day=-1)
        # print(nowData(minute=-cls.prdt_time))
        r = requests.post(url, data=jsonData, headers=header)
        if r.status_code != 200:
            return None, '接口请求失败' + json.dumps(r.json(), ensure_ascii=False)
        resData = r.json()
        # print(resData)
        if resData['status'] != True:
            return None, '接口请求失败' + json.dumps(r.json(), ensure_ascii=False)
        data = {}
        data['data'] = resData['data']["rows"]
        data['pageNo'] = resData['data']["pageNo"]
        data['lastPage'] = resData['data']["lastPage"]
        data['totalCount'] = resData['data']["totalCount"]
        data['lastPage'] = resData['data']["lastPage"]
        return data, None

    @classmethod
    def moRkAddPost(cls, data):
        """

        :param data: 表身参数
        :param token: 请求头token
        :return:
        """
        url = cls.apiAdd + "v2/eky4/im/im_mdc_mftmanuinbill/batchSave"
        jsonData = data
        # pprint(jsonData)
        # print(json.dumps(jsonData,ensure_ascii=False))
        token, err = cls.getToken()
        if err is not None:
            return None, '获取token失败' + err
        header = {
            # "Content-Type": "application/json",
            "accesstoken": token,
            "x-acgw-identity": str(cls.xacgwidentity)
        }
        # jsonData['start_eky4_shrq'] = nowData(minute=-cls.prdt_time, day=-1)
        # print(nowData(minute=-cls.prdt_time))
        r = requests.post(url, json=jsonData, headers=header)
        if r.status_code != 200:
            return None, '接口请求失败' + json.dumps(r.json(), ensure_ascii=False)
        resData = r.json()
        # print(resData)
        if resData['status'] != True:
            return None, '接口请求失败' + json.dumps(r.json(), ensure_ascii=False)
        return resData, None